<template>
  <div class="home">
    <el-container>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="video-container">
              <div class="local-video">
                <div ref="localVideo" class="video-player">
                  <div class="video-placeholder" v-if="!isJoined">
                    <el-icon size="32"><VideoCamera /></el-icon>
                  </div>
                </div>
                <div class="video-label">本地视频</div>
              </div>
              <div class="remote-container">
                <template v-for="user in remoteUsers" :key="user.uid">
                  <div class="remote-video">
                    <div :id="`remote-${user.uid}`" class="video-player"></div>
                    <div class="video-label">远程用户 {{ user.uid }}</div>
                  </div>
                </template>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <el-card class="control-panel">
              <template #header>
                <div class="card-header">
                  <span>会议控制</span>
                </div>
              </template>
              
              <el-form :model="rtcConfig" label-width="100px">
                <el-form-item label="频道名">
                  <el-input v-model="rtcConfig.channel" :disabled="isJoined"></el-input>
                </el-form-item>
                
                <el-form-item label="用户名">
                  <el-input v-model="rtcConfig.userName" :disabled="isJoined"></el-input>
                </el-form-item>
              </el-form>

              <div class="control-buttons">
                <el-button-group>
                  <el-button 
                    type="primary" 
                    :icon="VideoPlay"
                    @click="joinChannel" 
                    :disabled="isJoined">
                    加入频道
                  </el-button>
                  <el-button 
                    type="danger" 
                    :icon="VideoPlay"
                    @click="leaveChannel" 
                    :disabled="!isJoined">
                    离开频道
                  </el-button>
                </el-button-group>

                <div class="media-controls">
                  <el-button
                    :type="isMicOn ? 'primary' : 'info'"
                    :icon="isMicOn ? 'Microphone' : 'MicrophoneSlash'"
                    circle
                    @click="toggleMic"
                    :disabled="!isJoined">
                  </el-button>
                  <el-button
                    :type="isCameraOn ? 'primary' : 'info'"
                    :icon="isCameraOn ? 'VideoCamera' : 'VideoCameraSlash'"
                    circle
                    @click="toggleCamera"
                    :disabled="!isJoined">
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoCamera, VideoPlay } from '@element-plus/icons-vue'
import AliRTC from 'aliyun-rtc-sdk'

const localVideo = ref(null)
const client = ref(null)
const isJoined = ref(false)
const isMicOn = ref(true)
const isCameraOn = ref(true)
const remoteUsers = ref([])

const rtcConfig = ref({
  channel: 'test-channel',
  userName: `user_${Math.floor(Math.random() * 1000000)}`,
  appId: '你的阿里云AppID',
  appKey: '你的阿里云AppKey'
})

// 初始化RTC客户端
const initRTCClient = () => {
  client.value = new AliRTC.createClient({
    mode: 'live',
    codec: 'h264',
    appId: rtcConfig.value.appId,
    appKey: rtcConfig.value.appKey
  })

  // 监听远程用户加入
  client.value.on('peer-join', (evt) => {
    ElMessage.success(`用户 ${evt.uid} 加入频道`)
  })

  // 监听远程用户离开
  client.value.on('peer-leave', (evt) => {
    ElMessage.info(`用户 ${evt.uid} 离开频道`)
    remoteUsers.value = remoteUsers.value.filter(user => user.uid !== evt.uid)
  })

  // 监听远程流发布
  client.value.on('stream-added', async (evt) => {
    const remoteStream = evt.stream
    await client.value.subscribe(remoteStream)
    
    remoteUsers.value.push({
      uid: remoteStream.getUserId(),
      stream: remoteStream
    })

    setTimeout(() => {
      remoteStream.play(`remote-${remoteStream.getUserId()}`)
    }, 100)
  })
}

// 加入频道
const joinChannel = async () => {
  try {
    await client.value.join({
      channel: rtcConfig.value.channel,
      user: rtcConfig.value.userName
    })

    const localStream = AliRTC.createStream({
      audio: true,
      video: true
    })

    await localStream.init()
    await client.value.publish(localStream)
    
    localStream.play(localVideo.value)
    isJoined.value = true
    ElMessage.success('成功加入频道')
  } catch (error) {
    ElMessage.error(`加入频道失败: ${error.message}`)
  }
}

// 离开频道
const leaveChannel = async () => {
  try {
    await client.value.leave()
    isJoined.value = false
    remoteUsers.value = []
    ElMessage.success('已离开频道')
  } catch (error) {
    ElMessage.error(`离开频道失败: ${error.message}`)
  }
}

// 切换麦克风
const toggleMic = async () => {
  try {
    await client.value.muteLocal('audio', isMicOn.value)
    isMicOn.value = !isMicOn.value
    ElMessage.success(isMicOn.value ? '麦克风已开启' : '麦克风已关闭')
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}

// 切换摄像头
const toggleCamera = async () => {
  try {
    await client.value.muteLocal('video', isCameraOn.value)
    isCameraOn.value = !isCameraOn.value
    ElMessage.success(isCameraOn.value ? '摄像头已开启' : '摄像头已关闭')
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}

onMounted(() => {
  initRTCClient()
})

onBeforeUnmount(() => {
  if (isJoined.value) {
    leaveChannel()
  }
})
</script>

<style scoped>
.home {
  padding: 20px;
}

.video-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-player {
  width: 100%;
  height: 300px;
  background-color: #1a1a1a;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.video-placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #666;
}

.local-video, .remote-video {
  position: relative;
}

.video-label {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.remote-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.control-panel {
  height: 100%;
}

.control-buttons {
  display: flex;
  flex-direction: column;
  gap: 20px;
  align-items: center;
  margin-top: 20px;
}

.media-controls {
  display: flex;
  gap: 10px;
}

.card-header {
  font-weight: bold;
}
</style>